package com.snow.useviewdemo.animation;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Shader;
import android.os.CountDownTimer;
import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;


/**
 * author : zyt
 * e-mail : 632105276@qq.com
 * date   : 2019/4/13
 * desc   :直播画对号的View
 */
public class LiveRightView extends View {

    private Paint mPaint;
    private PathMeasure mPathMeasure;

    /**
     * 截取的路径
     */
    private Path mDstPath;

    /**
     * Path 长度
     */
    private float mPathLength;

    /**
     * 动画估值
     */
    private float mAnimatorValue;

    /**
     * View 是个正方形，宽高中小的一个值,根据小的值来定位绘制
     */
    private int mRealSize;

    /**
     * 颜色
     */
    private int mStartColor = Color.WHITE;
    private int mEndColor = Color.WHITE;

    /**
     * 画笔宽度
     */
    private float mStrokeWidth = 40f;

    /**
     * 对号
     */
    private ValueAnimator mRightMarkValueAnimator;

    /**
     * 动画执行时间
     */
    public static final int ANIMATOR_TIME = 400;

    public LiveRightView(Context context) {
        super(context, null);
    }

    public LiveRightView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // 初始化画笔
        initPaint();
        initShader();
        initMarkAnimator();
    }

    /**
     * 开启动画
     */
    public void startAnimator() {
        new CountDownTimer(10, 10) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                mPaint.setColor(mStartColor);
                initRightMarkPath();
                mRightMarkValueAnimator.start();
            }
        }.start();
    }

    /**
     * 设置颜色
     */
    public void setColor(@ColorInt int startColor, @ColorInt int endColor) {
        this.mStartColor = startColor;
        this.mEndColor = endColor;
    }

    /**
     * 设置画笔粗细
     */
    public void setStrokeWidth(float strokeWidth) {
        this.mStrokeWidth = strokeWidth;
        mPaint.setStrokeWidth(mStrokeWidth);
    }

    /**
     * 绘制
     *
     * @param canvas 画布
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mDstPath == null) {
            return;
        }
        // 刷新当前截取 Path
//        mDstPath.reset();
        // 避免硬件加速的Bug
//        mDstPath.lineTo(0, 0);
        // 截取片段
        float stop = mPathLength * mAnimatorValue;
        mPathMeasure.getSegment(0.1f, stop, mDstPath, true);
        // 绘制截取的片段
        canvas.drawPath(mDstPath, mPaint);
    }

    /**
     * 当View从屏幕消失时，关闭可能在执行的动画，以免可能出现内存泄漏
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 取消对号动画
        boolean isRightMarkNeedCancel =
                (mRightMarkValueAnimator != null && mRightMarkValueAnimator.isRunning());
        if (isRightMarkNeedCancel) {
            mRightMarkValueAnimator.cancel();
        }
    }


    /**
     * 线性渐变
     */
    private void initShader() {
        // 使用线性渐变
        LinearGradient shader = new LinearGradient(0, 0, mRealSize, mRealSize,
                mStartColor, mEndColor, Shader.TileMode.REPEAT);
        mPaint.setShader(shader);
    }

    /**
     * 画笔
     */
    private void initPaint() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        // PathMeasure
        mPathMeasure = new PathMeasure();
        // Path dst 用来存储截取的Path片段
        mDstPath = new Path();
    }

    /**
     * 初始化对号动画
     */
    private void initMarkAnimator() {
        mRightMarkValueAnimator = ValueAnimator.ofFloat(0f, 1);
        // 动画过程
        mRightMarkValueAnimator.addUpdateListener(animation -> {
            mAnimatorValue = (float) animation.getAnimatedValue();
            invalidate();
        });

        // 动画时间
        mRightMarkValueAnimator.setDuration(ANIMATOR_TIME);

        // 插值器
        mRightMarkValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        mRightMarkValueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
//                 刷新当前截取 Path
                mPathLength = 0f;
                mDstPath.reset();
                invalidate();
                if (animationListener != null) {
                    animationListener.liveRightViewEnd();
                }
            }
        });
    }

    public void setLiveRightViewAnimation(LiveRightViewListener listener) {
        this.animationListener = listener;
    }

    private LiveRightViewListener animationListener;

    public interface LiveRightViewListener {
        void liveRightViewEnd();
    }

    /**
     * 关联对号 Path
     */
    private void initRightMarkPath() {
        if (mRealSize == 0) {
            mRealSize = getWidth();
        }
        Path path = new Path();
        // 对号起点
        float startX = (float) (0.1 * mRealSize);
        float startY = (float) (0.6 * mRealSize);
        path.moveTo(startX, startY);

        // 对号拐角点
        float cornerX = (float) (0.43 * mRealSize);
        float cornerY = (float) (0.90 * mRealSize);
        path.lineTo(cornerX, cornerY);

        // 对号终点
        float endX = (float) (0.90 * mRealSize);
        float endY = (float) (0.4 * mRealSize);
        path.lineTo(endX, endY);

        // 重新关联Path
        mPathMeasure.setPath(path, false);
        // 此时为对号 Path 的长度
        mPathLength = mPathMeasure.getLength();
    }
}
